<template>
  <div class="form-group">
    <label class="file-label">
      <input
        type="file"
        :accept="accept"
        :multiple="multiple"
        @change="handleChange"
        class="file-input"
      />
      <span class="file-btn">选择{{ title }}</span>
    </label>
    <div class="file-tip">支持 {{ accept.replace(/\./g, '').replace(/,/g, ', ') }} 格式</div>
    <div v-if="file && !multiple" class="file-info">
      <span>{{ file.name }}</span>
      <button type="button" class="btn-link" @click="() => $emit('remove')">移除</button>
    </div>
    <div v-if="file && multiple" class="file-info">
      <span>已选择 {{ file.length }} 个文件</span>
      <button type="button" class="btn-link" @click="() => $emit('remove')">移除全部</button>
    </div>
    <div v-if="previewUrl && !multiple" class="cover-preview">
      <img :src="previewUrl" alt="{{ title }}预览" />
    </div>
    <div v-if="error" class="error-message">{{ error }}</div>
  </div>
</template>

<script setup>
import { defineProps, defineEmits } from 'vue'

const props = defineProps({
  title: { type: String, required: true },
  accept: { type: String, required: true },
  file: { type: Object, default: null },
  error: { type: String, default: '' },
  previewUrl: { type: String, default: '' },
  multiple: { type: Boolean, default: false },
})

const emit = defineEmits(['change', 'remove'])

const handleChange = (event) => {
  if (event.target.files && event.target.files[0]) {
    if (props.multiple) {
      emit('change', Array.from(event.target.files))
    } else {
      emit('change', event.target.files[0])
    }
  }
}
</script>

<style scoped>
.form-group {
  margin-bottom: 20px;
  position: relative;
}

.file-label {
  display: block;
  position: relative;
  overflow: hidden;
  margin-bottom: 10px;
}

.file-btn {
  display: inline-block;
  padding: 12px 20px;
  background-color: #ffffff;
  border: 2px dashed #27ae60;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  color: #27ae60;
  font-weight: 500;
  font-size: 14px;
  width: 100%;
  text-align: center;
}

.file-btn:hover {
  background-color: #e8f5e9;
  border-style: solid;
  border-color: #27ae60;
  color: #27ae60;
}

.file-input {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
}

.file-tip {
  font-size: 12px;
  color: #999;
  margin-bottom: 10px;
}

.file-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #f9f9f9;
  border-radius: 4px;
  font-size: 14px;
}

.btn-link {
  color: #27ae60;
  background: transparent;
  border: none;
  padding: 0;
  cursor: pointer;
  font-size: 14px;
}

.btn-link:hover {
  text-decoration: underline;
}

.cover-preview {
  margin-top: 15px;
  display: flex;
  justify-content: center;
}

.cover-preview img {
  max-width: 100%;
  max-height: 200px;
  border-radius: 4px;
}

.error-message {
  color: #e74c3c;
  font-size: 12px;
  margin-top: 5px;
}
</style>
